#include <iostream>
#include <unistd.h>     // fork(),getpid()
#include <sys/wait.h>   // waitpid()
#include <sys/types.h>  // getpid(),getppid()
//#include <stdlib.h>     // (type)pid_t

using namespace std;

void test1()
{
    pid_t id = fork();
    if(id == 0)     // child_process
    {
        int cnt = 5;
        while(cnt)
        {
            printf("I am child process, pid: %d, ppid: %d, cnt: %d\n", getpid(), getppid(), cnt);
            --cnt;
        }
        exit(1);
    }

    // father_process
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);

        // print by (status&0x7F), (status>>8)&0xFF)
    //if(rid > 0)
    //{
    //    printf("wait success, rid: %d, status: %d, exit singno: %d, exit code: %d\n",
    //                rid, status, (status&0x7F), (status>>8)&0xFF);
    //}
    
        // print by WIFEXITED(status) and WEXITSTATUS(status)
    
    if(WIFEXITED(status))
    {
        printf("wait success, rid: %d, status: %d, exit code: %d\n", rid, status, 
                                                            WEXITSTATUS(status));
    }
    else{
        printf("child process error!\n");
    }
}


void test2()
{
    pid_t id = fork();
    if(id == 0)     // child_process
    {
        int cnt = 5;
        while(cnt)
        {
            printf("I am child process, pid: %d, ppid: %d, cnt: %d\n", getpid(), getppid(), cnt);
            --cnt;
        }
        exit(1);
    }

    // father_process
    int status = 0;
    int count = 0;
    while(true)
    {
        pid_t rid = waitpid(id, &status, WNOHANG);
        if(rid > 0)
        {
            printf("wait success, rid: %d, status: %d, exit code: %d\n", rid, status, 
                                                            WEXITSTATUS(status));
            break;
        }
        else if(rid == 0)
        {
            printf("Waiting: child is running...\n");
            count++;        // father_process can do other things
        }
        else{
            perror("waitpid");
            break;
        }
    }
    cout << "father process add_count = " << count << endl;

}


int main()
{
    //test1();
    test2();
    

    return 0;
}


